<?php
/**
 * This class is not finished. It is just copied from BankLink library. (OLD)
* @package PankLink
* @author Jesper Saron, Oliver Leisalu
* @package BankLink
*/
final class DomBankLink_Nordea extends DomBankLink {
	
	/**
	* Private key.
	* @var String
	*/
	protected $privateKey;
	/**
	* Reseller identification code
	* @var String
	*/
	protected $resellerId;
	/**
	* Account number
	* @var String
	*/
	protected $resellerAccount;
	/**
	* Account owner
	* @var String
	*/
	protected $resellerName;
	/**
	* Server to where request is sent.
	* @var String
	*/
	protected $serverUrl;
	/**
	* Url to where user is sent back from bank
	* @var String
	*/
	protected $callbackUrl;
	/**
	 * @var String
	 */
	protected $outputEncoding = 'ISO-8859-1';
	/**
	 * @var String
	 */
	protected $inputEncoding = 'UTF-8';

	
	public function getName() {
		return 'Nordea';
	}
	
	public function getKey() {
		return 'nordea';
	}
	
	public function getIconUrl() {
		return DOM_URL . '../libsPub/DomBankLink/images/Nordea.gif';
	}
	
	/**
	 * Function returns all the input fields required by the bank using BankPayment object.
	 *
	 * @param BankPayment $payment
	 * @return string HTML including input=hidden tags
	 */
	public function sendToBank( DomBankLinkObject $payment ) {
		
		if( $payment instanceof DomBankPayment ) {
			if ( strpos($payment->price, ",") ) {
				$payment->price = (float)str_replace(",", ".", $payment->price);
			}
			
			$_SESSION['_PANKLINK_NORDEA_PRICE'] = $payment->price;
			
		
			$rsField = array(
				'SOLOPMT_VERSION'    => '0003',
	            'SOLOPMT_STAMP'      => $payment->id,
	            'SOLOPMT_RCV_ID'     => $this->resellerId,
				'SOLOPMT_RCV_ACCOUNT'        => $this->resellerAccount,
	            'SOLOPMT_RCV_NAME'       => $this->resellerName,
				'SOLOPMT_LANGUAGE' 	 => "4",
				'SOLOPMT_AMOUNT'     => $payment->price,
				'SOLOPMT_REF'        => $this->referenceNumber($payment->id),
				'SOLOPMT_DATE'		 => 'EXPRESS',
	            'SOLOPMT_CURR'       => $payment->currency,
	            'SOLOPMT_MSG'        => $payment->description,
				'SOLOPMT_RETURN'     => $this->getCallBackUrl( $payment ),
				'SOLOPMT_CANCEL'     => $this->getCallBackUrl( $payment ),
				'SOLOPMT_REJECT'     => $this->getCallBackUrl( $payment ),
				'SOLOPMT_CONFIRM'    => 'YES',
				'SOLOPMT_KEYVERS'	 => '0001',
				'SOLOPMT_CUR'		 => $payment->currency
	       	);
	
	       	$rsField['SOLOPMT_MAC'] = strtoupper(md5(
	       		$rsField['SOLOPMT_VERSION'] . "&" .
	       		$rsField['SOLOPMT_STAMP'] . "&" .
	       		$rsField['SOLOPMT_RCV_ID'] . "&" .
	       		$rsField['SOLOPMT_AMOUNT'] . "&" .
	       		$rsField['SOLOPMT_REF'] . "&" .
	       		$rsField['SOLOPMT_DATE'] . "&" .
	       		$rsField['SOLOPMT_CUR'] . "&" .
	       		$this->privateKey . "&"));
	       		
		} else if( $payment instanceof DomBankIdentify ) {
			$rsField = array(
				'A01Y_ACTION_ID'    => '701',
				'A01Y_VERS'  		=> '0002',
				'A01Y_RCVID' 		=> $this->resellerId,
				'A01Y_LANGCODE' 	=> 'ET',
				'A01Y_STAMP' 		=> $payment->id,
				'A01Y_IDTYPE' 		=> '02',
				'A01Y_RETLINK' 		=> $this->getCallBackUrl( $payment ),
				'A01Y_CANLINK' 		=> $this->getCallBackUrl( $payment ),
				'A01Y_REJLINK' 		=> $this->getCallBackUrl( $payment ),
				'A01Y_KEYVERS' 		=> '0001',
				'A01Y_ALG' 		=> '01',
	       	);
		
	       	
	       	$key = $rsField['A01Y_ACTION_ID'] . "&" .
	       		$rsField['A01Y_VERS'] . "&" .
	       		$rsField['A01Y_RCVID'] . "&" .
	       		$rsField['A01Y_LANGCODE'] . "&" .
	       		$rsField['A01Y_STAMP'] . "&" .
	       		$rsField['A01Y_IDTYPE'] . "&" .
	       		$rsField['A01Y_RETLINK'] . "&" .
	       		$rsField['A01Y_CANLINK'] . "&" .
	       		$rsField['A01Y_REJLINK'] . "&" .
	       		$rsField['A01Y_KEYVERS'] . "&" .
	       		$rsField['A01Y_ALG'] . "&" .
	       		$this->privateKey . "&";

	       	$rsField['A01Y_MAC'] = strtoupper(md5($key));
			
		}
    	$fields = '';
    	foreach ($rsField as $ixField => $fieldValue) {
    		$fields .= '<input type="hidden" name="' . $ixField . '" value="' . htmlspecialchars(iconv($this->inputEncoding, $this->outputEncoding, $fieldValue)) . '" />' . "\n";
    	}
    	
    	$form = '
			<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
			<html xmlns="http://www.w3.org/1999/xhtml">
			<head>
			<meta http-equiv="Content-Type" content="text/html; charset='.$this->outputEncoding.'" />
			<title>Suunamine</title>
			</head>
			<body>
			<form id="form" action="'.$this->serverUrl.'" method="POST">
				'.$fields.'
				<input type="submit" value="Edasi panka"/>
			</form>
			<script type="text/javascript"> t = setTimeout( "document.getElementById(\"form\").submit()" ,500 ); </script>	
			</body>
			</html>';
    	
    	echo $form;
		die();
	}
	/**
	 * Function that processes the callback from the bank and returns BankPayment objects with isSuccessful
	 * (and other applicable) parameters filled according to the answers from the bank.
	 *
	 * @return BankPayment
	 */
	public function handleReplay( $paymentClassName, $requestId = NULL ) {
		$rsField = array();

		
		if( $_REQUEST['SOLOPMT_RETURN_STAMP'] > 0 ) {
	   		$requestId = $_REQUEST['VK_STAMP'];
		}
		
		$payment = DomAr::load( $requestId, $paymentClassName );
		
		if( !$payment )
			return false;
			
		if( $payment->status != DomBankPayment::SENT_TO_BANK )
			return $payment;
			
		// identification request
		if( array_key_exists('B02K_VERS', $_REQUEST)) {
			foreach ((array)$_REQUEST as $ixField => $fieldValue) {
		        if (substr($ixField, 0, 5) == 'B02K_') {
		            $rsField[$ixField] = $fieldValue;
		        }
		    }
		    
			$key = strtoupper(md5(
				$rsField['B02K_VERS'] . "&" .
				$rsField['B02K_TIMESTMP'] . "&" .
				$rsField['B02K_IDNBR'] . "&" .
				$rsField['B02K_STAMP'] . "&" .
				$rsField['B02K_CUSTNAME'] . "&" .
				$rsField['B02K_KEYVERS'] . "&" .
				$rsField['B02K_ALG'] . "&" .
				$rsField['B02K_CUSTID'] . "&" .
				$rsField['B02K_CUSTTYPE'] . "&" .
				$this->privateKey . "&"));

			// Invalid signature
			if ($key != $rsField['B02K_MAC']) {
				$payment->status = 3;
	
			// successful payment 
			} else if ( $rsField['B02K_CUSTNAME'] ) {
				$payment->status = 1;
			
		   // Payment was cancelled
		    } else {
				$payment->status = 2;
		    }
		    

			
			$payment->clientCode = $rsField['B02K_CUSTID'];
			$payment->clientName =  strtoupper( $rsField['B02K_CUSTNAME'] );

		   
		} else {
		    foreach ((array)$_REQUEST as $ixField => $fieldValue) {
		        if (substr($ixField, 0, 8) == 'SOLOPMT_') {
		            $rsField[$ixField] = $fieldValue;
		        }
		    }
		
			$key = strtoupper(md5($rsField['SOLOPMT_RETURN_VERSION'] . "&" .$rsField['SOLOPMT_RETURN_STAMP'] . "&" .$rsField['SOLOPMT_RETURN_REF'] . "&" .$rsField['SOLOPMT_RETURN_PAID'] . "&" .$this->privateKey . "&"));
			
			// Invalid signature
			if ($key != $rsField['SOLOPMT_RETURN_MAC']) {
				$payment->status = 3;
	
			// successful payment 
			} else if ( isset($rsField['SOLOPMT_RETURN_PAID']) ) {
				$payment->status = 1;
			
		   // Payment was cancelled
		    } else {
				$payment->status = 2;
		    }
		    
		    //$payment->clientAccountNr = $rsField['VK_SND_ACC'];
			//$payment->clientName = strtoupper($rsField['VK_SND_NAME']);
		}
		
		$payment->backTime = 'now';
		$payment->backIp = ip();
		
		if( !$payment->save() ) {
			throw new RuntimeException( $payment->getValidationMessages('<br>') );
		}
		
		return $payment;
	}

	/**
	* @internal
	*/
	protected function referenceNumber($ixOrder) {
		# reference number calculation using the algorithm provided by Pankade liit
		$rsMultiplier = array (7, 3, 1);
		$ixCurrentMultiplier = 0;
		$sixOrder = (string) $ixOrder;
		for ($i = strlen($sixOrder)-1; $i >= 0; $i--)
		{
			$rsProduct[$i] = substr($sixOrder, $i, 1)*$rsMultiplier[$ixCurrentMultiplier];
			if ($ixCurrentMultiplier == 2)
			{
				$ixCurrentMultiplier = 0;
			}
			else
			{
				$ixCurrentMultiplier++;
			}
		}
		$sumProduct = 0;
		foreach ($rsProduct as $product)
		{
			$sumProduct += $product;
		}
		if ($sumProduct % 10 == 0)
		{
			$ixReference = 0;
		}
		else
		{
			$ixReference = 10 - ($sumProduct % 10);
		}
		return $sixOrder.$ixReference;
	}
}
?>